package com.m2bshop.shop.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.m2bshop.shop.pojo.User;
import com.m2bshop.shop.pojo.dto.LoginDTO;
import com.m2bshop.shop.pojo.dto.RegisterDTO;
import com.m2bshop.shop.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/***
 * 登录控制器
 * @date   2022/6/12 0012 8:47
 * @author JackeyTower
 */
@Controller
public class LoginController {

    private UserService userService;
    private static final String KEY = "1124667252855678";

    public LoginController(UserService userService) {
        this.userService = userService;
    }

    //拦截index页面
    @RequestMapping("/")
    public String indexHandler() {
        return "testlayui";
    }

    //登录v1
    @RequestMapping(value = "/userlogin", method = RequestMethod.POST)
    public ModelAndView loginHandler(User user, HttpSession session) {
        ModelAndView mav = new ModelAndView();
//        if(user.getUsername()!=null) {
//            User user1 = userService.findUserByUserName(user.getUsername());
//            if (user1 == null) {
//                mav.setViewName("login");
//                mav.addObject("error","用户不存在");
//            } else if (!(user.getPassword().equals(user1.getPassword()))){
//                mav.setViewName("login");
//                mav.addObject("error","密码输入有误");
//            }else {
//                session.setAttribute("uName",user.getUsername());
//                session.setAttribute("userId",user1.getId());
//                session.setAttribute("user", user1);
//                mav.setViewName("sys_admin");
//            }
//        }
        System.out.println(user);
        mav.setViewName("sys_admin");
        return mav;
    }

    //跳转到test页面
    @RequestMapping("/test")
    public String test() {
        return "test";
    }

    //跳转到注册页面
    @RequestMapping("/register")
    public String register() {
        return "register";
    }

    //跳转到注册页面
    @RequestMapping("/user-register")
    public ModelAndView userRegisterHandler(HttpServletRequest request, RegisterDTO registerDTO , HttpSession session) {
        System.out.println(registerDTO);
        ModelAndView modelAndView = new ModelAndView();
        User oldUser1 = userService.getUserByUsername(registerDTO.getUsername());
        //参数基本校验
        String username = registerDTO.getUsername();
        if (username.length()>50){
            System.out.println("用户名过长");
            modelAndView.setViewName("register");
            modelAndView.addObject("error","用户名过长");
            return modelAndView;
        }
        if (oldUser1!=null){
            System.out.println("用户名已存在！");
            modelAndView.setViewName("register");
            modelAndView.addObject("error","用户已存在");
            return modelAndView;
        }
        User oldUser2 = userService.getUserByPhonenumber(registerDTO.getPhonenumber());
        if (oldUser2!=null){
            System.out.println("手机号已被使用");
            modelAndView.setViewName("register");
            modelAndView.addObject("error","手机号已被使用");
            return modelAndView;
        }

        //将password加密
        //使用用户名生成key
        SecretKey secretKeySource = SecureUtil.generateKey("AES",KEY.getBytes());
        //生成AES加密对象，对信息进行加密
        AES aes = SecureUtil.aes(secretKeySource.getEncoded());
        String encryptPassword = aes.encryptBase64(registerDTO.getPassword());

        User newUser = new User();
        BeanUtils.copyProperties(registerDTO,newUser);
        newUser.setPassword(encryptPassword);
        System.out.println(newUser);
        //将用户注册至系统
        userService.save(newUser);
        modelAndView.setViewName("testlayui");
        return modelAndView;
    }


    //登录v2
    @RequestMapping("/lay/login")
    @ResponseBody
    public Map<String,Object> login2(HttpServletRequest request, LoginDTO loginDTO ,HttpSession session){
        System.out.println(loginDTO);
        HashMap<String, Object> data = new HashMap<>();
        System.out.println("登录中");
        //查询用户信息
        User user = userService.getUserByUsername(loginDTO.getUsername());
        if (user==null){
            data.put("code",0);
            data.put("message","请输入数据");
            return data;
        }
        //密码校验
        //密码解密
        String username = loginDTO.getUsername();
        SecretKey secretKeySource = SecureUtil.generateKey("AES",KEY.getBytes());
        AES aes = SecureUtil.aes(secretKeySource.getEncoded());
        String truePassword = aes.decryptStrFromBase64(user.getPassword());
        //比对密码
        if (!truePassword.equals(loginDTO.getPassword())){
            data.put("code",0);
            data.put("message","密码错误");
            return data;
        }
        //校验角色
        if (!user.getRole().equals(loginDTO.getRole())){
            data.put("code",0);
            data.put("message","角色错误");
            return data;
        }
        //存放用户信息
        session.setAttribute("username",user.getUsername());
        session.setAttribute("role",user.getRole());
        session.setAttribute("userId",user.getId());
        data.put("code",1);
        //跳转到指定页面
        if (user.getRole().equals("bvo")){
            data.put("url","bvohome");
        }else if (user.getRole().equals("mvo")){
            data.put("url","mvohome");
        }else if(user.getRole().equals("adm")){
            data.put("url","home");
        }else {
            data.put("url","");
        }

        return data;
    }

    //跳转到系统管理员主页
    @RequestMapping("/home")
    public String toSysHome(HttpSession session) {
        String role = session.getAttribute("role")+"";
        if (!role.equals("adm")){
            session.removeAttribute("role");
            session.removeAttribute("userId");
            session.removeAttribute("username");
            return "testlayui";
        }
        return "sys_admin";
    }

    //跳转到借卖方主页
    @RequestMapping("/bvohome")
    public String toBvoHome(HttpSession session) {
        String role = session.getAttribute("role")+"";
        if (!role.equals("bvo")){
            session.removeAttribute("role");
            session.removeAttribute("userId");
            session.removeAttribute("username");
            return "testlayui";
        }
        return "bvo_home";
    }

    //跳转到品牌商主页
    @RequestMapping("/mvohome")
    public String toMvoHome(HttpSession session) {
        String role = session.getAttribute("role")+"";
        System.out.println(role);
        if (!role.equals("mvo")){
            session.removeAttribute("role");
            session.removeAttribute("userId");
            session.removeAttribute("username");
            return "testlayui";
        }
        return "mvo_home";
    }

}
